package com.yangxf.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

@Service
public class PaymentService {

    //========================服务降级

    public String pamentInfo_ok(int id){
        return Thread.currentThread().getName() + "" + "id:" + id + "ok";
    }

    @HystrixCommand(fallbackMethod = "pamentInfo_errorHandle",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000") // 3秒之内认为是正常的，没有问题
    }) // 兜底方法
    public String pamentInfo_error(int id){
        try {
            //TimeUnit.SECONDS.sleep(2);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "" + "id:" + id + "error";
    }

    public String pamentInfo_errorHandle(int id){
        return "原方法抛异常了，我是备用方法o(╥﹏╥)o  pamentInfo_errorHandle";
    }

    //===========================服务熔断      在10秒内请求次数达到10，失败6次以上，则熔断
    @HystrixCommand(fallbackMethod = "pamentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), // 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), // 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), // 失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") int id){
        if(id < 0){
            throw new RuntimeException("id不能是负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName() + "调用成功，流水号：" + serialNumber;
    }
    public String pamentCircuitBreaker_fallback(@PathVariable("id") int id){
        return "id 不能是负数，请稍后再试，┭┮﹏┭┮";
    }
}
